/**
 Brainfuck-Robots Bluetooth App
 Copyright (C) <2014>  <Simon Grafenhorst>

 This file is part of the Brainfuck-Robots Bluetooth App.

 The Brainfuck-Robots Bluetooth App is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 The Brainfuck-Robots Bluetooth App is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with the Brainfuck-Robots Bluetooth App.  If not, see <http://www.gnu.org/licenses/>.
 */
package de.brainfuckrobots.bluetooth;

import java.io.IOException;
import java.util.UUID;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.util.Log;
import android.widget.Toast;

public class ConnectThread extends Thread implements Runnable {

    private String tag = "ConnectThread";
    private BluetoothSocket socket;
    private final static String uuid = "00001101-0000-1000-8000-00805F9B34FB";
    private CommunicationThread communicationThread;

    public ConnectThread(BluetoothDevice device) {
        try {
            socket = device.createRfcommSocketToServiceRecord(UUID.fromString(uuid));
        } catch (IOException e) {
        }
    }

    public void run() {
        BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
        try {
            socket.connect();
        } catch (IOException connectException) {
            Log.e(tag, "Exception thrown at connecting");
            MainActivity.getContext().showToast(R.string.restartRoboter);
            try {
                socket.close();
            } catch (IOException closeException) {
                Log.e(tag, "Exception thrown at closing connection");
            }
            MainActivity.getContext().discover(null);
            return;
        }
        Log.i(tag, "starting communication");
        MainActivity.getContext().runOnUiThread(new Runnable() {
            @Override
            public void run() {
                MainActivity.getContext().showToast(R.string.connected);
            }
        });
        communicationThread = new CommunicationThread(socket);
        MainActivity.getContext().setCommunicationThread(communicationThread);
        communicationThread.execute();

    }

    public BluetoothSocket getSocket() {
        return socket;
    }

    public void cancel() {
        try {
            socket.close();
        } catch (IOException e) {
        }
    }

    public CommunicationThread getCommunicationThread() {
        return communicationThread;
    }
}

